package com.njupt.yanglonglong.report.demo.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.njupt.yanglonglong.report.demo.common.Result;
import com.njupt.yanglonglong.report.demo.entity.Course;
import com.njupt.yanglonglong.report.demo.entity.Experiment;
import com.njupt.yanglonglong.report.demo.entity.RUser;
import com.njupt.yanglonglong.report.demo.service.CourseService;
import com.njupt.yanglonglong.report.demo.service.ExperimentService;
import com.njupt.yanglonglong.report.demo.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

/**
 * @Author yangllong
 * @Date 2021/4/25 18:03
 */
@Slf4j
@CrossOrigin
@RestController
public class CourseController {

    @Resource
    private CourseService courseService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private ExperimentService experimentService;

    @PostMapping("/queryCourseList")
    public Result<JSONObject> queryCourseList(@RequestBody HashMap<String, String> map) {
        JSONObject data = new JSONObject();
        JSONArray list;
        String courseName = map.get("courseName");
        List<Course> courseList;
        courseList = courseService.findAll(Objects.requireNonNullElse(courseName, ""));
        int count = courseList.size();
        String courseStr = JSON.toJSONString(courseList);
        list = (JSONArray) JSON.parse(courseStr);
        data.put("courses", list);
        data.put("total", count);
        return Result.success(data);
    }

    @PostMapping("/getCoursesByTeacherId")
    public Result<JSONObject> getCoursesByTeacherId(HttpServletRequest request) {
        JSONObject res = new JSONObject();
        JSONArray list;
        String token = request.getHeader("Authorization");
        RUser user = redisUtil.getUser(token);
        if (user == null) {
            res.put("msg", "用户权限校验失败，请先登录");
            return Result.error(res);
        }
        String teacherId = user.getUserId();
        List<Course> courseList;
        courseList = courseService.getCoursesByTeacherId(teacherId);
        int count = courseList.size();
        String courseStr = JSON.toJSONString(courseList);
        list = (JSONArray) JSON.parse(courseStr);
        res.put("courses", list);
        res.put("total", count);
        return Result.success(res);
    }

    @PostMapping("/getExperimentByTeacherId")
    public Result<JSONObject> getExperimentByTeacherId(HttpServletRequest request) {
        JSONObject res = new JSONObject();
        JSONArray list;
        String token = request.getHeader("Authorization");
        RUser user = redisUtil.getUser(token);
        if (user == null) {
            res.put("msg", "用户权限校验失败，请先登录");
            return Result.error(res);
        }
        String teacherId = user.getUserId();
        List<Course> courseList = courseService.getCoursesByTeacherId(teacherId);
        JSONArray courseAndExperiments = new JSONArray();
        for (Course c :
                courseList) {
            List<Experiment> experimentList = experimentService.getExperimentListByCourseId(c.getCourseId());
            JSONObject course = new JSONObject();
            if (experimentList.size() != 0) {
                JSONArray experiments = new JSONArray();
                course.put("value", c.getCourseId());
                course.put("label", c.getCourseName());
                for (Experiment e :
                        experimentList) {
                    JSONObject experiment = new JSONObject();
                    experiment.put("value", e.getExperId());
                    experiment.put("label", e.getExperName());
                    experiments.add(experiment);
                }
                course.put("children", experiments);
                courseAndExperiments.add(course);
            }
        }
        int count = courseAndExperiments.size();
        String courseAndExperimentStr = JSON.toJSONString(courseAndExperiments);
        list = (JSONArray) JSON.parse(courseAndExperimentStr);
        res.put("courseAndExperimentStr", list);
        res.put("total", count);
        return Result.success(res);
    }

    @PostMapping("/getExperiment")
    public Result<JSONObject> getExperiment(HttpServletRequest request) {
        JSONObject res = new JSONObject();
        JSONArray list;
        String token = request.getHeader("Authorization");
        RUser user = redisUtil.getUser(token);
        if (user == null) {
            res.put("msg", "用户权限校验失败，请先登录");
            return Result.error(res);
        }
        List<Course> courseList = courseService.findAll("");
        JSONArray courseAndExperiments = new JSONArray();
        for (Course c :
                courseList) {
            List<Experiment> experimentList = experimentService.getExperimentListByCourseId(c.getCourseId());
            JSONObject course = new JSONObject();
            if (experimentList.size() != 0) {
                JSONArray experiments = new JSONArray();
                course.put("value", c.getCourseId());
                course.put("label", c.getCourseName());
                for (Experiment e :
                        experimentList) {
                    JSONObject experiment = new JSONObject();
                    experiment.put("value", e.getExperId());
                    experiment.put("label", e.getExperName());
                    experiments.add(experiment);
                }
                course.put("children", experiments);
                courseAndExperiments.add(course);
            }
        }
        int count = courseAndExperiments.size();
        String courseAndExperimentStr = JSON.toJSONString(courseAndExperiments);
        list = (JSONArray) JSON.parse(courseAndExperimentStr);
        res.put("courseAndExperimentStr", list);
        res.put("total", count);
        return Result.success(res);
    }

    @PostMapping("/addCourse")
    public Result<JSONObject> addCourse(@RequestBody Course course) {
        JSONObject res = new JSONObject();
        try {
            courseService.addCourse(course);
        } catch (DuplicateKeyException e) {
            log.info("课程编号不可重复" + e);
            res.put("msg", "课程编号不可重复");
            return Result.error(res);
        }
        res.put("msg", "添加成功");
        return Result.success(res);
    }

    @PostMapping("/deleteCourse")
    public Result<JSONObject> deleteCourse(@RequestBody Course course) {
        JSONObject res = new JSONObject();
        try {
            boolean flag = courseService.deleteCourse(course);
            if (!flag) {
                res.put("msg", "教师已选课，无法删除");
                log.info("教师已选课，无法删除");
                return Result.error(res);
            }
            log.info("[删除课程成功] id:" + course.getCourseId());
        } catch (Exception e) {
            log.info("删除失败" + e);
            res.put("msg", "删除课程失败");
            return Result.error(res);
        }
        res.put("msg", "删除课程成功");
        return Result.success(res);
    }

    @PostMapping("/editCourse")
    public Result<JSONObject> editCourse(@RequestBody Course course) {
        JSONObject res = new JSONObject();
        try {
            courseService.editCourse(course);
        } catch (DuplicateKeyException e) {
            log.error("课程编号不可重复" + e);
            res.put("msg", "课程编号不可重复");
            return Result.error(res);
        }
        res.put("msg", "修改成功");
        log.info("[修改课程成功]" + course.getCourseId());
        return Result.success(res);
    }

    /**
     * 查询学生已经选上的课程
     *
     * @param request stuId
     * @return courseList
     */
    @RequestMapping("/queryStuCourse")
    public Result<JSONObject> queryStuCourse(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        RUser user = redisUtil.getUser(token);
        JSONObject res = new JSONObject();
        log.info("/queryStuCourse接到请求，user：" + user);

        List<Course> courseList = courseService.queryStudentCourseList(user.getUserId());
        if (courseList == null) {
            res.put("msg", "获得课程列表失败");
            return Result.error(res);
        }
        res.put("data", courseList);
        return Result.success(res);
    }

}
